package com.ssmtest.mybatis.service;

import com.ssmtest.mybatis.dao.EmployeeMapper;
import com.ssmtest.mybatis.entities.Employee;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/11/13 16:34
 */
@Slf4j
@Service
public class EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private SqlSession session;

    @Transactional(readOnly = true)
    public List<Employee> getAllEmps() {
        return employeeMapper.getAllEmps();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void batchAddEmps(List<Employee> employees) {
        try {
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
            employees.forEach(employee -> {
                mapper.addEmp(employee);
            });
            session.commit();
        } catch (Exception e) {
            log.error("batchAddEmps error", e);
        } finally {
            session.close();
        }
    }
}
